<template>
    <div class="notification-management">
      <h2>通知提醒管理</h2>
      
      <!-- 通知筛选表单 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="通知标题">
            <el-input v-model="searchForm.title" placeholder="请输入通知标题"></el-input>
          </el-form-item>
          <el-form-item label="通知类型">
            <el-select v-model="searchForm.type" placeholder="请选择通知类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="系统通知" value="system"></el-option>
              <el-option label="工单提醒" value="workOrder"></el-option>
              <el-option label="任务通知" value="task"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="已发送" value="sent"></el-option>
              <el-option label="未发送" value="unsent"></el-option>
              <el-option label="失败" value="failed"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发送时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="openCreateDialog">创建通知</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 通知列表 -->
      <el-table :data="filteredNotifications" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="通知ID" width="100"></el-table-column>
        <el-table-column prop="title" label="通知标题" width="200"></el-table-column>
        <el-table-column prop="type" label="通知类型" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column prop="sendTime" label="发送时间"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewNotification(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editNotification(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteNotification(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right"
      ></el-pagination>
  
      <!-- 创建通知弹窗 -->
      <el-dialog
        v-model="createDialogVisible"
        title="创建通知"
        width="50%"
      >
        <el-form :model="notificationForm" label-width="120px">
          <el-form-item label="通知标题">
            <el-input v-model="notificationForm.title"></el-input>
          </el-form-item>
          <el-form-item label="通知类型">
            <el-select v-model="notificationForm.type" placeholder="请选择通知类型">
              <el-option label="系统通知" value="system"></el-option>
              <el-option label="工单提醒" value="workOrder"></el-option>
              <el-option label="任务通知" value="task"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="通知内容">
            <el-input v-model="notificationForm.content" type="textarea" :rows="4"></el-input>
          </el-form-item>
          <el-form-item label="接收者">
            <el-select v-model="notificationForm.recipients" multiple placeholder="请选择接收者">
              <el-option label="张三" value="zhangsan"></el-option>
              <el-option label="李四" value="lisi"></el-option>
              <el-option label="王五" value="wangwu"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发送时间">
            <el-date-picker
              v-model="notificationForm.sendTime"
              type="datetime"
              placeholder="选择发送时间"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="createDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitNotification">发送</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 通知详情弹窗 -->
      <el-dialog
        v-model="detailDialogVisible"
        :title="currentNotification.title"
        width="50%"
      >
        <el-form label-width="120px">
          <el-form-item label="通知ID">
            <el-input v-model="currentNotification.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="通知类型">
            <el-input v-model="currentNotification.type" disabled></el-input>
          </el-form-item>
          <el-form-item label="通知内容">
            <el-input v-model="currentNotification.content" type="textarea" :rows="4" disabled></el-input>
          </el-form-item>
          <el-form-item label="接收者">
            <el-tag v-for="recipient in currentNotification.recipients" :key="recipient" style="margin-right: 10px">{{ recipient }}</el-tag>
          </el-form-item>
          <el-form-item label="发送时间">
            <el-input v-model="currentNotification.sendTime" disabled></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-input v-model="currentNotification.status" disabled></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="resendNotification" v-if="currentNotification.status !== 'sent'">重新发送</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // 模拟通知数据
  const notifications = ref([
    {
      id: 'NT-001',
      title: '系统维护通知',
      type: 'system',
      content: '系统将于2023-10-15进行维护，请提前做好准备。',
      recipients: ['张三', '李四'],
      sendTime: '2023-10-01 10:00',
      status: 'sent'
    },
    {
      id: 'NT-002',
      title: '工单提醒',
      type: 'workOrder',
      content: '有新的工单需要处理，请及时查看。',
      recipients: ['王五'],
      sendTime: '2023-10-02 14:30',
      status: 'sent'
    },
    {
      id: 'NT-003',
      title: '任务通知',
      type: 'task',
      content: '请完成本周的任务报告。',
      recipients: ['张三', '李四', '王五'],
      sendTime: '2023-10-03 09:00',
      status: 'failed'
    }
  ])
  
  // 查询表单数据
  const searchForm = ref({
    title: '',
    type: '',
    status: '',
    dateRange: []
  })
  
  // 分页相关变量
  const currentPage = ref(1)
  const pageSize = ref(5)
  const total = ref(notifications.value.length)
  
  // 过滤后的通知
  const filteredNotifications = computed(() => {
    const { title, type, status, dateRange } = searchForm.value
    let filtered = notifications.value
  
    // 标题过滤
    if (title) {
      filtered = filtered.filter(item => item.title.includes(title))
    }
  
    // 类型过滤
    if (type) {
      filtered = filtered.filter(item => item.type === type)
    }
  
    // 状态过滤
    if (status) {
      filtered = filtered.filter(item => item.status === status)
    }
  
    // 日期范围过滤
    if (dateRange.length) {
      const [start, end] = dateRange
      filtered = filtered.filter(item => {
        const itemDate = new Date(item.sendTime)
        const startDate = new Date(start)
        const endDate = new Date(end)
        return itemDate >= startDate && itemDate <= endDate
      })
    }
  
    return filtered
  })
  
  // 更新总条目数
  watch(filteredNotifications, () => {
    total.value = filteredNotifications.value.length
    currentPage.value = 1
  })
  
  // 创建通知弹窗
  const createDialogVisible = ref(false)
  
  // 通知详情弹窗
  const detailDialogVisible = ref(false)
  
  // 当前通知详情
  const currentNotification = ref({
    id: '',
    title: '',
    type: '',
    content: '',
    recipients: [],
    sendTime: '',
    status: ''
  })
  
  // 通知表单数据
  const notificationForm = ref({
    title: '',
    type: '',
    content: '',
    recipients: [],
    sendTime: new Date()
  })
  
  // 打开创建通知弹窗
  const openCreateDialog = () => {
    notificationForm.value = {
      title: '',
      type: '',
      content: '',
      recipients: [],
      sendTime: new Date()
    }
    createDialogVisible.value = true
  }
  
  // 提交通知
  const submitNotification = () => {
    if (!notificationForm.value.title || !notificationForm.value.type || !notificationForm.value.content || !notificationForm.value.recipients.length) {
      ElMessage.error('请填写所有必填字段')
      return
    }
  
    const newNotification = {
      id: `NT-${Date.now()}`,
      title: notificationForm.value.title,
      type: notificationForm.value.type,
      content: notificationForm.value.content,
      recipients: notificationForm.value.recipients,
      sendTime: formatDate(notificationForm.value.sendTime),
      status: 'sent'
    }
  
    notifications.value.push(newNotification)
    ElMessage.success('通知发送成功！')
    createDialogVisible.value = false
  }
  
  // 查看通知详情
  const viewNotification = (row: any) => {
    currentNotification.value = { ...row }
    detailDialogVisible.value = true
  }
  
  // 编辑通知
  const editNotification = (row: any) => {
    notificationForm.value = { ...row }
    createDialogVisible.value = true
  }
  
  // 删除通知
  const deleteNotification = (row: any) => {
    ElMessageBox.confirm('确定要删除这条通知吗？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      notifications.value = notifications.value.filter(item => item.id !== row.id)
      ElMessage.success('通知删除成功！')
    }).catch(() => {
      ElMessage.info('删除已取消')
    })
  }
  
  // 重新发送通知
  const resendNotification = () => {
    currentNotification.value.status = 'sent'
    ElMessage.success('通知重新发送成功！')
    detailDialogVisible.value = false
  }
  
  // 查询按钮点击事件
  const handleSearch = () => {
    total.value = filteredNotifications.value.length
    currentPage.value = 1
  }
  
  // 重置按钮点击事件
  const resetSearch = () => {
    searchForm.value = {
      title: '',
      type: '',
      status: '',
      dateRange: []
    }
    total.value = notifications.value.length
    currentPage.value = 1
  }
  
  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
  }
  
  // 当前页变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
  }
  
  // 格式化日期
  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  }
  </script>
  
  <style scoped>
  .notification-management {
    padding: 20px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .demo-form-inline {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
  </style>